

function insert_block(){ //插入一个设备数组块
   // '<block type="math_number"><field name="NUM">100</field></block>';
   
    var newBlock = 
    '<block type="variables_set">\<field name="VAR" >DEV' + device_id + '</field>' +
      '<value name="VALUE">\
        <block type="device_array" inline="false">\
          <mutation items="5"/>\
          <value name="ADD0">\
            <block type="text">\
              <field name="TEXT">客厅空调</field>\
            </block>\
          </value>\
          <value name="ADD1">\
            <block type="text">\
              <field name="TEXT">温度</field>\
            </block>\
          </value>\
          <value name="ADD2">\
            <block type="text">\
              <field name="TEXT">1/1/2</field>\
            </block>\
          </value>\
          <value name="ADD3">\
            <block type="math_number">\
              <field name="NUM">8</field>\
            </block>\
          </value>\
          <value name="ADD4">\
            <block type="math_number">\
              <field name="NUM">24</field>\
            </block>\
          </value>\
        </block>\
      </value>\
      <next>\
        <block type="send_value">\
          <value name="Device">\
            <block type="variables_get">\
              <field name="VAR" >DEV' + device_id + '</field>' +
             '</block>\
          </value>\
        </block>\
      </next>\
    </block>\
    '


    device_id = device_id + 1;
    $("#startBlocks").append(newBlock);
    Blockly.Xml.domToWorkspace(document.getElementById('startBlocks'), demoWorkspace);
    newBlock = '';
}



function generateCodeAndLoadIntoInterpreter() {  //拼图转js代码
  var lua_code= '';
  lua_code = Blockly.Lua.workspaceToCode(demoWorkspace);
  return lua_code;
}

function TransCode(){
  edit_code = Blockly.Lua.workspaceToCode(demoWorkspace);
  lua_edit_area.value =  edit_code;
}

function SaveCode() {
  if(edit_code.length < 3){   // 如果编辑框没有代码 自动从逻辑块转化代码报错
    output_code = generateCodeAndLoadIntoInterpreter();
    if(output_code.length > 2){ 
      lua_edit_area.value =  output_code;
      setTimeout(function() {  // 保存到文件
        output_code = head_code + output_code;
        var file = new File([output_code], "output.lua", { type: "text/plain;charset=UTF-16" }); //ISO-8859-1 utf-16
        saveAs(file);
      }, 100);
    } else {  // 如果逻辑块也没代码 报提示
      window.alert("请先转换或输入代码");
    }
  }else{ // 编辑框有代码直接保存
    output_code= edit_code;
    setTimeout(function() {  // 保存到文件
        output_code = head_code + output_code;
        var file = new File([output_code], "output.lua", { type: "text/plain;charset=UTF-16" }); //ISO-8859-1 utf-16
        saveAs(file);
      }, 100);
  }      
}